//
//  MainViewController.m
//  Main_TEST
//
//  Created by Centling on 14-5-27.
//  Copyright (c) 2014年 centling.org. All rights reserved.
//

#import "MainViewController.h"

#import "AFCollectionViewFlowLargeLayout.h"
#import "AFCollectionViewFlowSmallLayout.h"
#import "AFCollectionViewSmallCell.h"
#import "AFCollectionViewLargeCell.h"
#import "QTSearchViewController.h"
#import "QTProductDetailViewController.h"
#import "QTQualityInfoViewController.h"
#import "MHTabBarController.h"
#import "CodaBarScanViewController.h"
#import "QTClient.h"
#import "UIImageView+UIActivityIndicatorForSDWebImage.h"
#import "QTQualityListViewController.h"
#import "QTDetailCategory.h"
#import "QTArticle.h"
#import "Global.h"
#import "QTInfoDetailViewController.h"

#import "QTUserDefault.h"

#define IS_IHONE4 ([UIScreen mainScreen].bounds.size.height == 480)

@interface MainViewController ()

@property (nonatomic, strong) AFCollectionViewFlowLargeLayout *largeLayout;
@property (nonatomic, strong) AFCollectionViewFlowSmallLayout *smallLayout;
@property (nonatomic, strong) NSArray *images;

@end


static NSString *ItemIdentifier = @"AFCollectionViewSmallCell";
static NSString *ItemIdentifier2 = @"AFCollectionViewLargeCell";


@implementation MainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}


-(void)viewWillAppear:(BOOL)animated
{
    //if (article == nil)
    {
        [[QSClient instance] loadNewsList:@2 startIndex:@1 maxResults:@4 productTypePuid:@"" completionBlock:^(NSArray *articleList, NSError *error){
            article =[[NSMutableArray alloc ]initWithArray:articleList];
            [self.largeCollectionView reloadData];
        }];
        
    }

    [self.hidenTabBarDelegate hideTabBar:NO];
    
    self.smallLayout = [[AFCollectionViewFlowSmallLayout alloc] init];
    self.largeLayout = [[AFCollectionViewFlowLargeLayout alloc] init];
    
    
    [self.smallCollectionView setCollectionViewLayout:self.smallLayout];
    [self.smallCollectionView registerClass:[AFCollectionViewSmallCell class] forCellWithReuseIdentifier:ItemIdentifier];
    self.smallCollectionView.delegate = self;
    self.smallCollectionView.dataSource = self;
    self.smallCollectionView.tag = 10;
    
    self.smallCollectionView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
    
    [self.largeCollectionView setCollectionViewLayout:self.smallLayout];
    [self.largeCollectionView registerClass:[AFCollectionViewLargeCell class] forCellWithReuseIdentifier:ItemIdentifier2];
    self.largeCollectionView.delegate = self;
    self.largeCollectionView.dataSource = self;
    self.largeCollectionView.tag = 20;
    
    self.largeCollectionView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
//    [[QSClient instance] loadNewsList:@4 startIndex:@1 maxResults:@4 productTypePuid:@"" completionBlock:^(NSArray *articleList, NSError *error){
//        article =[[NSMutableArray alloc ]initWithArray:articleList];
//        [self.largeCollectionView reloadData];
//    }];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [[QSClient instance] mainPagePic:^(QTDetailCategory *DetailCategory, NSError *error)
     {
         if ([DetailCategory.indexFlashs count] > 0)
         {
             IndexFlashs * indexFlashs=(IndexFlashs*)[DetailCategory.indexFlashs objectAtIndex:0];
             NSURL *picURL=[NSURL URLWithString:[self convertPicURL:indexFlashs.imagePath]];
             // [self.advertisementPic setImageWithURL:[NSURL URLWithString:[self convertPicURL:picURL]]];
             
             [self.advertisementPic setImageWithURL:picURL completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
                 if (image == nil) {
                     NSLog(@"could not load the pic");
                 }
             } usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray ];
             
         }
     }];
    
    
    self.navigationItem.title=@"质量查询";
    // Do any additional setup after loading the view from its nib.
    //    self.searchTextField.placeholder = @"搜一搜，哪便宜";
    //    [self.searchTextField setLeftViewMode:UITextFieldViewModeAlways];
    //    UIImage *countLeftImageOrg = [UIImage imageNamed:@"08.png"];
    //    CGRect countRect = CGRectMake(0.0, 0.0, self.searchTextField.frame.size.height/2, self.searchTextField.frame.size.height/2);
    //    UIGraphicsBeginImageContext(countRect.size);
    //    [countLeftImageOrg drawInRect:countRect];
    //    UIImage *countLeftImageFinal = UIGraphicsGetImageFromCurrentImageContext();
    //    UIGraphicsEndImageContext();
    //    UIImageView *countLeftImageView =[[UIImageView alloc] initWithImage:countLeftImageFinal];
    //    self.searchTextField.leftView= countLeftImageView;
    
    self.searchButton.layer.cornerRadius = 5;
    self.searchButton.backgroundColor = [UIColor whiteColor];
    
    UIImage *imageButtonImageOrg = [UIImage imageNamed:@"08.png"];
    CGRect countRect = CGRectMake(0.0, 0.0, 20, 20);
    UIGraphicsBeginImageContext(countRect.size);
    [imageButtonImageOrg drawInRect:countRect];
    UIImage *imageButtonImageFinal = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    [self.searchButton setImage: imageButtonImageFinal forState: UIControlStateNormal];
    [self.searchButton setTitle:@"搜一搜" forState:UIControlStateNormal];
    self.searchButton.tintColor = [UIColor colorWithRed:0.0 green:255.0 blue:100.0 alpha:0.5f];
    [self.searchButton setImageEdgeInsets: UIEdgeInsetsMake(0, -170, 0, 0)];
    [self.searchButton setTitleEdgeInsets: UIEdgeInsetsMake(0, -160, 0, 0)];
    
    
    if (IS_IHONE4)
    {
        self.mainScrollView.contentSize = CGSizeMake(320.0, 538.0);
        self.mainScrollView.scrollEnabled = YES;
        
        //        self.largeCollectionView.scrollEnabled = YES;
        //
        //        CGFloat largeCVHeight = self.largeCollectionView.frame.size.height;
        //        CGFloat largeCVWidth = self.largeCollectionView.frame.size.width;
        //        CGFloat largeCVX = self.largeCollectionView.frame.origin.x;
        //        CGFloat largeCVY = self.largeCollectionView.frame.origin.y;
        //
        //        [self.largeCollectionView setFrame:CGRectMake(largeCVX, largeCVY, largeCVWidth, largeCVHeight-78)];
    }
    else
    {
        self.mainScrollView.scrollEnabled = NO;
    }
}


#pragma mark - UICollectionView DataSource & Delegate methods

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 4;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    UICollectionViewCell *  baseCell;
    
    if (collectionView.tag == 10)
    {
        AFCollectionViewSmallCell *cell = (AFCollectionViewSmallCell *)[collectionView dequeueReusableCellWithReuseIdentifier:ItemIdentifier forIndexPath:indexPath];
        //        if (cell == nil) {
        //            cell = [[AFCollectionViewSmallCell alloc] init];
        //        }
        if (indexPath.row == 0)
        {
            cell.cellImageView.image = [UIImage imageNamed:@"comp.png"];
            cell.cellTopLabel.text = @"条码比价";
            cell.cellBottomLabel.text = @"扫一扫，哪便宜";
        }
        else if (indexPath.row == 1)
        {
            cell.cellImageView.image = [UIImage imageNamed:@"check.png"];
            cell.cellTopLabel.text = @"质量监督";
            cell.cellBottomLabel.text = @"质量.安全随时看";
        }
        
        baseCell = cell;
        
    }
    
    
    else if (collectionView.tag == 20)
    {
        
        //Delay the pic load to the tableview
        
        AFCollectionViewLargeCell *cell = (AFCollectionViewLargeCell *)[collectionView dequeueReusableCellWithReuseIdentifier:ItemIdentifier2 forIndexPath:indexPath];
        cell.userInteractionEnabled = NO;
 
        UIView *view = nil;
        if (indexPath.row == 0 )
        {
            [activityIndicator0 stopAnimating];
            activityIndicator0.hidden = YES;
            
            if ([article count] > 0) {
                NSURL *picURL=[NSURL URLWithString:[self convertPicURL:((QTArticle *)[article objectAtIndex:0]).thumbImgPath]];
                [cell.cellImageView setImageWithURL:picURL completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
                    if (image == nil) {
                        NSLog(@"could not load the pic");
                        [cell.cellImageView setImage:[UIImage imageNamed:@"暂无图片.png"]];
                    }
                } usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray ];
                cell.cellTopLabel.text = ((QTArticle *)[article objectAtIndex:0]).articleTitle;
                cell.puid=((QTArticle *)[article objectAtIndex:0]).puid;
                cell.userInteractionEnabled=YES;

            }
            else if ([article count] == 0)
            {
                cell.userInteractionEnabled=NO;
                if ( activityIndicator0 == nil) {
                    //加载数据的时候加上一个indicator----------
                    activityIndicator0 = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                    activityIndicator0.autoresizingMask = UIViewAutoresizingNone;
                    CGRect activityIndicatorBounds = activityIndicator0.bounds;
                    float x = (cell.frame.size.width - activityIndicatorBounds.size.width) / 2.0;
                    float y = (cell.frame.size.height - activityIndicatorBounds.size.height) / 2.0;
                    activityIndicator0.frame = CGRectMake(x, y, activityIndicatorBounds.size.width, activityIndicatorBounds.size.height);
                    [cell addSubview:activityIndicator0];
                    [activityIndicator0 startAnimating];
                    //加载数据的时候加上一个indicator----------
                }
                else
                {
                    [cell.cellImageView setImage:[UIImage imageNamed:@"暂无图片.png"]];
                }

            }
            
        }
        else if (indexPath.row == 1 )
        {
            [activityIndicator1 stopAnimating];
            activityIndicator1.hidden = YES;
            
            if ([article count] > 0) {
                NSURL *picURL=[NSURL URLWithString:[self convertPicURL:((QTArticle *)[article objectAtIndex:1]).thumbImgPath]];
                [cell.cellImageView setImageWithURL:picURL completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
                    if (image == nil) {
                        NSLog(@"could not load the pic");
                        [cell.cellImageView setImage:[UIImage imageNamed:@"暂无图片.png"]];
                    }
                } usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray ];
                cell.cellTopLabel.text = ((QTArticle *)[article objectAtIndex:1]).articleTitle;
                cell.puid=((QTArticle *)[article objectAtIndex:1]).puid;
                cell.userInteractionEnabled=YES;

            }
            else if ([article count] == 0)
            {

                cell.userInteractionEnabled=NO;
                if ( activityIndicator1 == nil) {
                    //加载数据的时候加上一个indicator----------
                    activityIndicator1 = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                    activityIndicator1.autoresizingMask = UIViewAutoresizingNone;
                    CGRect activityIndicatorBounds = activityIndicator1.bounds;
                    float x = (cell.frame.size.width - activityIndicatorBounds.size.width) / 2.0;
                    float y = (cell.frame.size.height - activityIndicatorBounds.size.height) / 2.0;
                    activityIndicator1.frame = CGRectMake(x, y, activityIndicatorBounds.size.width, activityIndicatorBounds.size.height);
                    [cell addSubview:activityIndicator1];
                    [activityIndicator1 startAnimating];
                    //加载数据的时候加上一个indicator----------
                }
                else
                {
                    [cell.cellImageView setImage:[UIImage imageNamed:@"暂无图片.png"]];
                }
                
            }
        }
        else if (indexPath.row == 2 )
        {
            [activityIndicator2 stopAnimating];
            activityIndicator2.hidden = YES;
            
            if ([article count] > 0) {
                NSURL *picURL=[NSURL URLWithString:[self convertPicURL:((QTArticle *)[article objectAtIndex:2]).thumbImgPath]];
                [cell.cellImageView setImageWithURL:picURL completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
                    if (image == nil) {
                        NSLog(@"could not load the pic");
                        [cell.cellImageView setImage:[UIImage imageNamed:@"暂无图片.png"]];
                    }
                } usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray ];
                cell.cellTopLabel.text = ((QTArticle *)[article objectAtIndex:2]).articleTitle;
                cell.puid=((QTArticle *)[article objectAtIndex:2]).puid;
                cell.userInteractionEnabled=YES;

            }
            else if ([article count] == 0)
            {
                
                cell.userInteractionEnabled=NO;
                if ( activityIndicator2 == nil) {
                    //加载数据的时候加上一个indicator----------
                    activityIndicator2 = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                    activityIndicator2.autoresizingMask = UIViewAutoresizingNone;
                    CGRect activityIndicatorBounds = activityIndicator2.bounds;
                    float x = (cell.frame.size.width - activityIndicatorBounds.size.width) / 2.0;
                    float y = (cell.frame.size.height - activityIndicatorBounds.size.height) / 2.0;
                    activityIndicator2.frame = CGRectMake(x, y, activityIndicatorBounds.size.width, activityIndicatorBounds.size.height);
                    [cell addSubview:activityIndicator2];
                    [activityIndicator2 startAnimating];
                    //加载数据的时候加上一个indicator----------
                }
                else
                {
                    [cell.cellImageView setImage:[UIImage imageNamed:@"暂无图片.png"]];
                }
                
            }
        }
        else if (indexPath.row == 3 )
        {
            [activityIndicator3 stopAnimating];
            activityIndicator3.hidden = YES;
            
            if ([article count] > 0) {
                NSURL *picURL=[NSURL URLWithString:[self convertPicURL:((QTArticle *)[article objectAtIndex:3]).thumbImgPath]];
                [cell.cellImageView setImageWithURL:picURL completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
                    if (image == nil) {
                        NSLog(@"could not load the pic");
                        [cell.cellImageView setImage:[UIImage imageNamed:@"暂无图片.png"]];
                    }
                } usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray ];
                cell.cellTopLabel.text = ((QTArticle *)[article objectAtIndex:3]).articleTitle;
                cell.puid=((QTArticle *)[article objectAtIndex:3]).puid;
                cell.userInteractionEnabled=YES;

            }
            else if ([article count] == 0)
            {
                
                cell.userInteractionEnabled=NO;
                if ( activityIndicator3 == nil) {
                    //加载数据的时候加上一个indicator----------
                    activityIndicator3 = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                    activityIndicator3.autoresizingMask = UIViewAutoresizingNone;
                    CGRect activityIndicatorBounds = activityIndicator3.bounds;
                    float x = (cell.frame.size.width - activityIndicatorBounds.size.width) / 2.0;
                    float y = (cell.frame.size.height - activityIndicatorBounds.size.height) / 2.0;
                    activityIndicator3.frame = CGRectMake(x, y, activityIndicatorBounds.size.width, activityIndicatorBounds.size.height);
                    [cell addSubview:activityIndicator3];
                    [activityIndicator3 startAnimating];
                    //加载数据的时候加上一个indicator----------
                }
                else
                {
                    [cell.cellImageView setImage:[UIImage imageNamed:@"暂无图片.png"]];
                }
                
            }
        }
        
        baseCell = cell;
    }
    return baseCell;
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (collectionView.tag == 10)
    {
        if (indexPath.row == 0)
        {
            //进入二维码扫描界面
            CodaBarScanViewController *codaBarScanViewController = [[CodaBarScanViewController alloc] initWithNibName:@"CodaBarScanViewController" bundle:nil];
            codaBarScanViewController.title = @"扫码";
            UINavigationController *navCtrl = [[UINavigationController alloc] initWithRootViewController:codaBarScanViewController];
            [navCtrl.navigationBar setHidden:YES];
            [self presentViewController:navCtrl animated:YES completion:nil];
        }
        else if (indexPath.row == 1)
        {
            
            QTQualityListViewController *qualityListViewController=[[QTQualityListViewController alloc] init];
            
            UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:nil action:nil];
            self.navigationController.navigationBar.tintColor=[UIColor whiteColor];
            [self.navigationItem setBackBarButtonItem:backItem];
            [self.hidenTabBarDelegate hideTabBar:YES];
            [self.navigationController pushViewController:qualityListViewController animated:YES];
        }
    }
    else if (collectionView.tag==20) {
        
        UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:nil action:nil];
        self.navigationController.navigationBar.tintColor=[UIColor whiteColor];
        [self.navigationItem setBackBarButtonItem:backItem];
        
        QTInfoDetailViewController *infoDetailViewController=[[QTInfoDetailViewController alloc] init];
//        infoDetailViewController.puid=((AFCollectionViewLargeCell *)[[collectionView subviews] objectAtIndex:indexPath.row]).puid;
        infoDetailViewController.puid=((QTArticle *)[article objectAtIndex:indexPath.row]).puid;
        [self.hidenTabBarDelegate hideTabBar:YES];
        [self.navigationController pushViewController:infoDetailViewController animated:YES];
    }
}

-(NSString *)convertPicURL:(NSString *)url
{
    NSString *picURL=url;
    NSRange range_http = [url rangeOfString:@"http:"];
    NSRange range_HTTP = [url rangeOfString:@"HTTP:"];
    if ((range_http.length==0)&&(range_HTTP.length==0)) {
        NSString *serverUrl = @"http://60.209.238.28:8080/";
        picURL=[serverUrl stringByAppendingString:url==nil?@"":url];
    }
    return  picURL;
}

- (IBAction)gotoSearchView:(id)sender {
    QTSearchViewController* searchview = [[QTSearchViewController alloc ] init];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:nil action:nil];
    self.navigationController.navigationBar.tintColor=[UIColor whiteColor];
    [self.navigationItem setBackBarButtonItem:backItem];
    [self.hidenTabBarDelegate hideTabBar:YES];
    [self.navigationController pushViewController:searchview animated:YES];
}

- (IBAction)gotoscanvc:(id)sender {
    //进入二维码扫描界面
    CodaBarScanViewController *codaBarScanViewController = [[CodaBarScanViewController alloc] initWithNibName:@"CodaBarScanViewController" bundle:nil];
    codaBarScanViewController.title = @"扫码";
    UINavigationController *navCtrl = [[UINavigationController alloc] initWithRootViewController:codaBarScanViewController];
    [navCtrl.navigationBar setHidden:YES];
    [self presentViewController:navCtrl animated:YES completion:nil];

}


@end
